﻿using DotNetty.Transport.Channels;
using Microsoft.Extensions.Logging;
using System;
using System.Threading.Tasks;
namespace Athena.Transport.DotNetty.ChannelHandlerAdapers
{
    using Message;
    public class ServerChannelHandlerAdaper : ChannelHandlerAdapter
    {
        private readonly Action<IChannelHandlerContext, RpcTransportMessage> _channelReadAction;
        private readonly ILogger _logger;


        public ServerChannelHandlerAdaper(Action<IChannelHandlerContext, RpcTransportMessage> channelReadAction, ILogger logger)
        {
            _channelReadAction = channelReadAction;
            _logger = logger;
        }

        public override void ChannelRead(IChannelHandlerContext context, object message)
        {
            Task.Run(() =>
            {
                _channelReadAction(context, (RpcTransportMessage)message);
            });
        }

        public override void ChannelReadComplete(IChannelHandlerContext context)
        {
            context.Flush();
        }

        public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
        {
            context.CloseAsync();
            if (_logger.IsEnabled(LogLevel.Error))
            {
                _logger.LogError(exception, $"与服务器：{context.Channel.RemoteAddress}通出现异常。");
            }
        }
    }
}
